package gold.digger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/3/1.
 */
public class LC56 {

    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        List<int[]> res = new ArrayList<>();
        for (int[] interval : intervals) {
            int start = interval[0];
            int end = interval[1];
            if (res.size() <= 0 || res.get(res.size() - 1)[1] < start) {
                int[] newInterval = new int[2];
                newInterval[0] = start;
                newInterval[1] = end;
                res.add(newInterval);
            } else {
                res.get(res.size() - 1)[1] = Math.max(res.get(res.size() - 1)[1], end);
            }
        }
        return res.toArray(new int[res.size()][2]);
    }


    public static void main(String[] args) {
        LC56 an = new LC56();
        int[][] arr = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};

        System.out.println(an.merge(arr));
    }
}
